<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;


/**
 * 后端的接口，获取此控制器中的接口，每次都需要进行权限验证
 */

class User extends Controller
{
    //管理员登录
    public function login(Request $req){
        //暂时关闭登录
        $account = $req->account;
        $pwd = $req->pwd;
        $key = Cookie::get('admin');
        if($account==null && $key != null){
            //判断key是否正确
            $user = DB::table('user')->where('id',$key)->where('admin',1)->first(['id','account','email']);
            if($user){
                //添加日志
                Log::save($user->id,'登录');
                //更新一下登录记录
                DB::table('user')->where('id',$userdata->id)->update(['login_time',date('Y-m-d H:i:s')]);
                //正常允许登录
                return ['code'=>200,'message'=>'登录成功','data'=>$user];
            }else{
                return ['code'=>-2,'message'=>'你不是管理员或密码错误'];
            }
        }
        if($pwd == null){
            return ['code'=>-1,'message'=>'参数缺失'];
        }
        //进行登录判断
        $userdata = DB::table('user')->where('account',$account)->where('pwd',$pwd)->where('admin',1)->first(['id','account','email']);
        if($userdata){
            //这里应该设置cookie
            Cookie::queue('admin', $userdata->id, 60*24); // 一天
            //添加日志
            Log::save($userdata->id,'登录');
            //更新一下登录记录
            DB::table('user')->where('id',$userdata->id)->update(['login_time'=>date('Y-m-d H:i:s')]);
            return ['code'=>200,'message'=>'登录成功','data'=>$userdata];
        }else{
            return ['code'=>-2,'message'=>'你不是管理员或者密码错误'];
        }
    }

    //注册
    public function register(Request $req){
        $user = $req->user;
        $pwd = $req->pwd;
        $email = $req->email;
        if($user == null  || $pwd == null || $email==null){
            return ['code'=>-1,'message'=>'参数缺失'];
        }
        //查询下帐号是否存在
        if(DB::table('user')->where('account',$user)->first()){
            return ['code'=>-2,'message'=>'帐号已注册'];
        }
        $userdata = ['account'=>$user,'pwd'=>$pwd,'email'=>$email];
        //开始注册
        $user = DB::table('user')->insertGetId($userdata);
        if($user){
            //添加日志
            Log::save($user->id,'注册');
            return ['code'=>200,'message'=>'注册成功'];
        }else{
            return ['code'=>-1,'message'=>'注册失败'];
        }
    }

    //修改用户信息
    public function updateUser(Request $req){
        $user = $req->user;
        $data = [
            'pwd'=>$user['newpwd'],
            'email'=>$user['email'],
        ];
        //判断密码是否正确
        if(DB::table('user')->where('id',$user['id'])->where('pwd',$user['pwd'])->update($data)){
            return ['code'=>200,'message'=>'修改成功'];
        }else{
            return ['code'=>-1,'message'=>'原密码错误'];
        }


    }







}
